package com.jy.modules.cims.settle.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.util.StringUtils;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.exception.CimsException;
import com.jy.modules.cims.common.sysUtils.CollectionsUtils;
import com.jy.modules.cims.common.sysUtils.DateTimeUtils;
import com.jy.modules.cims.common.sysUtils.SearchParamUtil;
import com.jy.modules.cims.component.sysAssist.BatchService;
import com.jy.modules.cims.contract.service.ContractService;
import com.jy.modules.cims.creditright.service.CreditRightService;
import com.jy.modules.cims.creditright.service.SettleCreditService;
import com.jy.modules.cims.data.common.dto.TCMmCostPlanDTO;
import com.jy.modules.cims.data.dto.ContractAllDto;
import com.jy.modules.cims.data.dto.CreditDetailDto;
import com.jy.modules.cims.data.dto.CreditDetailQueryDto;
import com.jy.modules.cims.data.dto.CreditRightDto;
import com.jy.modules.cims.data.dto.DealDto;
import com.jy.modules.cims.data.dto.credit.CreditApplyDto;
import com.jy.modules.cims.deal.service.DealService;
import com.jy.platform.core.message.DataMsg;
import com.jy.platform.core.message.PageParameter;
import com.jy.platform.core.message.PageUtil;
import com.jy.platform.core.message.QueryReqBean;
import com.jy.platform.restservice.exception.AbaboonException;
import com.jy.platform.restservice.web.base.BaseController;

/**
 * 
 * ClassName: TransfereeSettleController 
 * @Description: 受让债权结算/异常结算
 * @author dell
 * @date 2015-7-28
 */
@Controller
@RequestMapping("/transfereeSettle")
public class TransfereeSettleController extends BaseController{
	public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
	
	@Autowired
    @Qualifier("com.jy.modules.cims.contract.service.ContractService")
    private ContractService serviceContract;

	@Autowired
	@Qualifier("com.jy.modules.cims.creditright.service.SettleCreditService")
	private SettleCreditService settleCreditService;
	

	@Autowired
	@Qualifier("com.jy.modules.cims.deal.service.DealService")
	public DealService dealService;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.creditright.service.CreditRightService")
	private CreditRightService creditRightService;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.sysAssist.BatchService")
	public BatchService batchService;
	

	@Autowired
	@Qualifier("com.jy.modules.cims.contract.service.ContractService")
	private ContractService contractService;
	
	@RequestMapping(value = "/prepareExecute/{operate}")
	public ModelAndView execute(@PathVariable("operate") String operate) throws AbaboonException {
		ModelAndView model = new ModelAndView();
		if("toQuery".equals(operate)){
			model.addObject("type", this.getParameterString("type"));
			model.addObject("bizType", CimsConstant.QUOTATYPE_CR);
			model.setViewName("cims/transfereeDeal/monthSettle/queryCreditTransferee");
		}else if("toAdd".equals(operate)){
			String settleType = this.getParameterString("settleType");
			model.addObject("bizType", CimsConstant.QUOTATYPE_CR);
			if(CimsConstant.DEAL_TYPE_CREDIT_NORMAL_SETTLE_REC.equals(settleType)){
				model.setViewName("cims/transfereeDeal/monthSettle/addMonthSettle");
			}else if(CimsConstant.DEAL_TYPE_CREDIT_ABNORMAL_SETTLE_REC.equals(settleType)){
				model.setViewName("cims/transfereeDeal/monthSettle/addCreditSettle");
			}
		}else if("toUpdate".equals(operate)){
			
		}else if("toViewCredit".equals(operate)){
			String dealCode = this.getParameterString("dealCode");
			model = this.queryOneDTO(dealCode);
			model.setViewName("cims/transfereeDeal/monthSettle/viewCreditSettle");
		}else if("toViewMonth".equals(operate)){
			String dealCode = this.getParameterString("dealCode");
			model = this.queryOneDTO(dealCode);
			model.setViewName("cims/transfereeDeal/monthSettle/viewMonthSettle");
		}else if("toQueryRedemp".equals(operate)){
			model.addObject("type", this.getParameterString("type"));
			model.addObject("bizType", CimsConstant.QUOTATYPE_CR);
			model.setViewName("cims/transfereeDeal/transferRedemp/queryTransferRedemp");
		}else if("toAddTransfereeRedemp".equals(operate)){
			model.addObject("bizType", CimsConstant.QUOTATYPE_CR);
			model.setViewName("cims/transfereeDeal/transferRedemp/addTransferRedemp");
		}else if("toBackTransfereeDealAdd".equals(operate)){ //合约确定-跳转至债权受让新增页面
        	String contractCode = this.getParameterString("contractCode");
        	model = serviceContract.queryAllDTO(contractCode);
        	model.setViewName("cims/transfereeDeal/transferRedemp/addTransferRedemp");
        }else if("toBackTransfereeDealUpdate".equals(operate)){//修改操作-跳转至债权受让修改页面
        	String cooperorgCode = this.getParameterString("cooperorgCode");
        	String contractCode = this.getParameterString("contractCode");
        	String dealCode = this.getParameterString("dealCode");
        	String idDeal = this.getParameterString("idDeal");
        	model = serviceContract.queryAllDTO(cooperorgCode,contractCode,dealCode);
        	model.addObject("idDeal", idDeal);
        	model.setViewName("cims/transfereeDeal/transferRedemp/updateTransfereeDeal");
        }
		return model;
	}
	
	/**
	 * 
	 * @Description 保存月还结算流水  -受让
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * DataMsg  
	 * @author zhangmi
	 * @date 2015-7-28
	 */
	@RequestMapping(value = "/saveTransfereeMonthSettle")
	@ResponseBody
	public DataMsg saveTransfereeMonthSettle(HttpServletRequest request, CreditDetailQueryDto dto, @ModelAttribute DataMsg dataMsg) {
		try {
			dto = (CreditDetailQueryDto) super.initDto(dto);
			List<String> planStatusList = new ArrayList<String>();
			planStatusList.add(dto.getPlanStatus());
			dto.setPlanStatusList(planStatusList);
			String dealCode = settleCreditService.doSettle(dto);
			dataMsg = super.initDataMsg(dataMsg);
			dataMsg.setMsg("保存成功！");
			dataMsg.setData(this.makeJSONData(dealCode));
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("保存失败：", e);
		}
		return dataMsg;
	}
	/**
	 * 
	 * @Title saveTransferRedemp
	 * @Description TODO
	 * 保存受让赎回流水
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @return 
	 * DataMsg 
	 * @author lizhiqiang
	 * @date 2016-2-22-下午6:22:50
	 * @update 
	 * @throws
	 */
	@RequestMapping(value = "/saveTransferRedemp")
	@ResponseBody
	public DataMsg saveTransferRedemp(HttpServletRequest request, DealDto dto, @ModelAttribute DataMsg dataMsg) {
		try {
			dto = (DealDto) super.initDto(dto);
			
			String dealCode = dto.getDealCode();
			String did = this.getParameterString("id");
			Long dealId = !StringUtils.hasText(did) ? null : Long.valueOf(did);
			if (StringUtil.isBlank(dto.getDealCode())) {
				// 创建交易流水信息
				StringBuffer dealCodesb = new StringBuffer();
				dealService.doGetTransferDealCode(dealCodesb);
				dealCode = dealCodesb.toString();
				dto.setDealCode(dealCode);
				dealId = dealService.saveTransferRedempDeal(dto);
				String redemptionStatus = "02";
				dealService.updateTcmmRedeemDetailByDealCode(dto,redemptionStatus);
			}
			
			Map<String, Object> resultMap = new HashMap<String, Object>();
			resultMap.put("id", dealId);
			resultMap.put("dealCode", dealCode);
			
			dataMsg = super.initDataMsg(dataMsg);
			dataMsg.setMsg("保存成功！");
			dataMsg.setData(resultMap);
			dataMsg.setStatus("ok");
		} catch (Exception e) {
			dataMsg.setStatus("error");
			dataMsg.failed(e.getMessage());
			logger.error("保存失败：", e);
		}
		return dataMsg;
	}
	/**
	 * 
	 * @Title saveTransferRedemp
	 * @Description TODO
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @return 
	 * DataMsg 
	 * @author lizhiqiang
	 * @date 2016-2-22-下午6:22:50
	 * @update 
	 * @throws
	 */
	@RequestMapping(value = "/confirmTransferRedemp")
	@ResponseBody
	public DataMsg confirmTransferRedemp(HttpServletRequest request, DealDto dto, @ModelAttribute DataMsg dataMsg) {
		try {
			dto = (DealDto) super.initDto(dto);
			
			String dealCode = dto.getDealCode();
			//1、调用受让赎回接口
			List<CreditDetailDto> cdlist = creditRightService.getCreditListByTransfereeRedemp(dto.getDealCode());
			Map<Object, Object> paramMap = new  HashMap<Object, Object>();
			paramMap.put("dto", dto);
			// 批量新增债权流水
			
			dealService.doBatchConfirmTransferRedemp(cdlist,paramMap);
			
			dataMsg = super.initDataMsg(dataMsg);
			dataMsg.setMsg("确认成功！");
		}catch (CimsException e) {
			dataMsg.failed(e.getMessage());
			dataMsg.setMsg(e.getMessage());
			logger.error("确认失败：", e);
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("确认失败：", e);
		}
		return dataMsg;
	}
	/**
	 * @Title getDealCreditDetailByPackage
	 * @Description TODO 查询受让包可以赎回的债权列表
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @return 
	 * DataMsg 
	 * @author lizhiqiang
	 * @date 2016-2-22-下午2:49:46
	 * @update 
	 * @throws
	 */
	@RequestMapping(value = "/getDealCreditDetailByPackage")
	@ResponseBody
	public DataMsg getDealCreditDetailByPackage(HttpServletRequest request, DealDto dto, @ModelAttribute DataMsg dataMsg) {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("dto", dto);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		List<CreditDetailDto> list = dealService.getDealCreditDetailByPackage(params.getSearchParams());
		dataMsg.setData(list);
		dataMsg.setTotalRows(pageInfo.getTotalCount());
		return dataMsg;
	}
	/**
	 * 
	 * @Description 根据交易流水号查询交易流水信息  --
	 * @param dealCode
	 * @throws AbaboonException   
	 * ModelAndView  
	 */
	private ModelAndView queryOneDTO(String dealCode) throws AbaboonException {
		ModelAndView model = new ModelAndView();
		try {
			CreditRightDto creditRightDto = null;
			Map<String, Object> searchParams = new HashMap<String, Object>();
			DealDto dealDto = new DealDto();
			dealDto.setDealCode(dealCode);
			searchParams.put("dto", dealDto);
			QueryReqBean params = new QueryReqBean();
			params.setSearchParams(searchParams);
			PageParameter pageInfo = PageUtil.toPageParameter(new DataMsg());
			params.setPageParameter(pageInfo);
			List<DealDto> dealDtoList = dealService.getDealList(params.getSearchParams());

			if (CollectionsUtils.isNotEmpty(dealDtoList)) {
				dealDto = dealDtoList.get(0);
				/* 查询合约信息 */
				ContractAllDto contractAllDto = contractService.getContractAllInfo(dealDto.getContractCode());
				model.addObject("contractAllDto", contractAllDto);
				model.addObject("dealCode", dealDto.getDealCode());

				creditRightDto = dealService.getDealDetailByCreditListByTotal(SearchParamUtil.getSearchParam(dealDto));
			}

			List<TCMmCostPlanDTO> costPlanList = settleCreditService.searchCostPlanByDealCode(dealCode);
			if (CollectionsUtils.isNotEmpty(costPlanList)) {
				TCMmCostPlanDTO costPlanPlanDto = costPlanList.get(0);
				model.addObject("costPlanPlanDto", costPlanPlanDto);
				model.addObject("settleDate", DateTimeUtils.formatDate(costPlanPlanDto.getStartDate(), DEFAULT_DATE_FORMAT));
			}else{
				model.addObject("settleDate", DateTimeUtils.formatDate(dealDtoList.get(0).getSettleDate(), DEFAULT_DATE_FORMAT));
			}

			model.addObject("dealDto", dealDtoList == null ? null : dealDtoList.get(0));
			model.addObject("creditRightDto", creditRightDto);

		} catch (Exception e) {
			throw new AbaboonException("执行queryOneDTO异常：", e);
		}
		return model;
	}
	
	/**
	 * 删除受让赎回流水，新建的流水可以删除
	 * @Title deleteDeal
	 * @Description TODO
	 * @param request
	 * @param dataMsg
	 * @return 
	 * DataMsg 
	 * @author lizhiqiang
	 * @date 2016-2-24-下午3:18:40
	 * @update 
	 * @throws
	 */
	@RequestMapping(value = "/deleteDeal")
	@ResponseBody
	public DataMsg deleteDeal(HttpServletRequest request, @ModelAttribute DataMsg dataMsg) {
		super.initDto(null);
		String dealCodes = (String) this.getParameter("dealCodes");// 格式: 1,2,3
		dataMsg = super.initDataMsg(dataMsg);
		try {
			dealService.deleteDealCode(dealCodes);
			dataMsg.setMsg("删除成功！");
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			dataMsg.setMsg("删除失败！"+e.getMessage());
			logger.error("执行方法creditDealController/deleteDeal异常：", e);
			//throw new CimsException(e.getMessage());
		}
		return dataMsg;
	}
	/**
	 * 导入
	 * @Title doTransfereeDeal
	 * @Description TODO
	 * @param request
	 * @param response
	 * @param dto
	 * @param dataMsg
	 * @return
	 * @throws Exception 
	 * DataMsg 
	 * @author lizhiqiang
	 * @date 2016-2-25-下午2:36:01
	 * @update 
	 * @throws
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/doTransfereeDeal")
	@ResponseBody
	public DataMsg doTransfereeDeal(HttpServletRequest request,HttpServletResponse response,CreditApplyDto dto, @ModelAttribute DataMsg dataMsg) throws Exception{
		try {
			String dataType = dto.getDataType() == null ? "" : dto.getDataType().trim();
			List<CreditDetailDto> creditDetailList = new ArrayList<CreditDetailDto>();
			if (CimsConstant.SESSION_IMPORT_DATA_PATH.equals(dataType)) {
				creditDetailList = (List<CreditDetailDto>) request.getSession().getAttribute(dto.getDataId());
			} 
			//检验excel数据
			dealService.doImportCheck(creditDetailList,dto);
			dto.setCreditDetailList(creditDetailList);
			dealService.updateTransferCreditCostValue(creditDetailList,dto);
			
			dataMsg.setData(dto);
			dataMsg.setStatus("ok");
			dataMsg.setMsg("调用creditDealService.doTransferee成功！");
		} catch (Exception e) {
			dataMsg.setStatus("error");
			dataMsg.setMsg(e.getMessage());
			request.getSession().removeAttribute(dto.getDataId());//从session中移除数据
			logger.error("执行方法creditDealService.doTransferee异常：", e);
			
		}
		return dataMsg;
	}
}
